import { Injectable } from '@nestjs/common';
import { Express } from 'express';
import { STORAGE_DESTINATION } from './constants/storage.constants';
import { createReadStream, existsSync, statSync, unlink, unlinkSync } from 'fs';
import { promisify } from 'util';
import * as path from 'path';
import * as sharp from 'sharp';
const unlinkAsync = promisify(unlink);

@Injectable()
export class FilesService {
  async saveFile(file: Express.Multer.File) {
    // 直接使用Multer保存的文件路径
    return {
      originalname: file.originalname,
      filename: file.filename,
      size: file.size,
      mimetype: file.mimetype,
      path: `/public/uploads/${file.filename}`,
    };
  }

  async processImage(file: Express.Multer.File) {
    const inputPath = path.join(STORAGE_DESTINATION, file.filename);
    const outputFilename = `thumb-${file.filename}`;
    const outputPath = path.join(STORAGE_DESTINATION, outputFilename);

    try {
      await sharp(inputPath).resize(300, 300).toFile(outputPath);

      // 删除原始文件
      await unlinkAsync(inputPath);

      return {
        originalname: file.originalname,
        filename: outputFilename,
        path: `/public/uploads/${outputFilename}`,
      };
    } catch (error) {
      // 如果Sharp处理失败，保留原始文件
      console.error('图片处理失败，使用原始文件:', error);
      return {
        originalname: file.originalname,
        filename: file.filename,
        path: `/public/uploads/${file.filename}`,
      };
    }
  }

  private async getSharp() {
    try {
      // 动态导入Sharp，如果不存在则返回null
      const sharp = await import('sharp');
      return sharp.default;
    } catch (error) {
      return null;
    }
  }

  async deleteFile(filename: string): Promise<boolean> {
    try {
      const filepath = path.join(STORAGE_DESTINATION, filename);
      if (existsSync(filepath)) {
        unlinkSync(filepath);
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  }

  async getFileInfo(filename: string) {
    try {
      const filepath = path.join(STORAGE_DESTINATION, filename);
      if (existsSync(filepath)) {
        const stats = statSync(filepath);
        return {
          filename,
          size: stats.size,
          created: stats.birthtime,
          modified: stats.mtime,
          path: `/public/uploads/${filename}`,
        };
      }
      return null;
    } catch (error) {
      return null;
    }
  }
}
